/**
 * 资讯服务模块
 */

// 使用统一配置辅助模块导入依赖
const serviceHelper = require('../../config/service_helper_config.js');
const { projectSetting, cloudHelper, dataHelper, timeHelper, BaseBiz } = serviceHelper;

/**
 * 资讯服务类
 */
class NewsService {

	/**
	 * 获取资讯分类
	 * @returns 资讯分类列表
	 */
	static getCateList() {
		let cateList = projectSetting.NEWS_CATE || [];
		let arr = [];
		for (let k = 0; k < cateList.length; k++) {
			arr.push({
				label: cateList[k].title,
				val: cateList[k].id,
			})
		}
		return arr;
	}

	/**
	 * 获取分类名称
	 * @param {*} cateId 分类ID
	 */
	static getCateName(cateId) {
		let cateList = projectSetting.NEWS_CATE || [];

		for (let k = 0; k < cateList.length; k++) {
			if (cateList[k].id == cateId) return cateList[k].title;
		}
		return '';
	}

	/**
	 * 获取资讯详情
	 * @param {*} id 资讯ID 
	 * @returns 资讯详情
	 */
	static async getNewsDetail(id) {
		let fields = '*';

		let where = {
			_id: id,
			NEWS_STATUS: 1
		}
		let news = await cloudHelper.callCloudData('news/detail', {
			where,
			fields
		});
		if (!news) return null;

		return news;
	}

	/**
	 * 获取资讯列表
	 * @param {*} param0 查询条件
	 * @returns 资讯列表
	 */
	static async getNewsList({
		cateId,
		search,
		sortType,
		sortVal,
		orderBy,
		page,
		size,
		isTotal = true,
		oldTotal
	}) {

		orderBy = orderBy || {
			'NEWS_ORDER': 'asc',
			'NEWS_ADD_TIME': 'desc'
		};
		let fields = '*';

		let where = {};
		where.NEWS_STATUS = 1; // 状态正常

		if (cateId && cateId !== '0') where.NEWS_CATE = cateId;
		
		if (search) {
			where.NEWS_TITLE = {
				$regex: '.*' + search,
				$options: 'i'
			};
		}

		return await cloudHelper.callCloudData('news/list', {
			where,
			fields,
			orderBy,
			page,
			size,
			isTotal,
			oldTotal
		});
	}

	/**
	 * 格式化日期
	 * @param {*} date 日期
	 */
	static getNewDateDesc(date) {
		if (!date) return '';
		let dateStr = timeHelper.timestamp2Time(date, 'Y-M-D');
		return dateStr;
	}
}

module.exports = NewsService; 